﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.ApplicationPages;
using Microsoft.SharePoint;
using System.Web.UI.WebControls;
using System.IO;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;
/*
 * 
 * Revision History
 * 
 * Date             Author          Modification
 * ----------       ----------      ----------
 * 09/30/2011       Paul Liebrand   Updated GenerateItem.aspx page to allow user to create custom short name.
 *
 */
namespace Liebrand.UrlShortener
{
    public partial class GenerateItem : LayoutsPageBase
    {

        #region Declarations

        protected TextBox TextBoxGeneratedUrl;
        protected TextBox InputFormTextBoxResult;
        protected Button ButtonOk;
        protected Button ButtonClose;
        protected CustomValidator CustomValidator1;
        protected Panel PanelStep1;
        protected Panel PanelStep2;

        #endregion

        #region Properties
        public string GeneratedShortUrl { get; set; }
        #endregion

        #region Methods

        protected override void OnLoad(EventArgs e)
        {
            if (Page.IsPostBack)
            {

            }

            base.OnLoad(e);
        }

        protected void ButtonOk_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                GeneratedShortUrl = string.Empty;

                if (string.IsNullOrEmpty(Request.QueryString["List"]))
                    GeneratedShortUrl = URLShortener.GenerateShortUrl(Request.QueryString["Source"], TextBoxGeneratedUrl.Text);
                else
                {
                    GeneratedShortUrl = URLShortener.GenerateShortUrl(SPContext.Current.Web.Lists[new Guid(Request.QueryString["List"])], int.Parse(Request.QueryString["ItemId"]), TextBoxGeneratedUrl.Text);
                }

                PanelStep1.Visible = false;
                PanelStep2.Visible = true;

                InputFormTextBoxResult.Text = GeneratedShortUrl;
            }
        }

        protected void ValidateCustomEntry(object source, ServerValidateEventArgs args)
        {
            if (args.Value.Length == 0)
            {
                args.IsValid = true;
                return;
            }

            args.IsValid = !URLShortener.DoesCustomNameExist(args.Value);

        }

        protected void ButtonClose_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(Request.QueryString["Source"]))
                return;

            SPUtility.Redirect(Request.QueryString["Source"], SPRedirectFlags.Default, Context);
        }
        #endregion

    }
}
